package com.gzsxy.esjy.service.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzsxy.esjy.common.base.exception.impl.CustomAssert;
import com.gzsxy.esjy.common.base.result.ResultCodeEnum;
import com.gzsxy.esjy.common.base.util.JwtInfo;
import com.gzsxy.esjy.common.base.util.JwtUtils;
import com.gzsxy.esjy.service.auth.dao.AddressMapper;
import com.gzsxy.esjy.service.auth.entity.Matedata;
import com.gzsxy.esjy.service.auth.service.AddressService;
import com.gzsxy.esjy.service.auth.shiro.config.CurrentUserUtil;
import com.gzsxy.esjy.service.base.DictionaryConstants;
import com.gzsxy.esjy.service.base.dto.request.AddressRequest;
import com.gzsxy.esjy.service.base.dto.response.MatedataRsp;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xiaolong
 * @version 1.0
 * @description: TODO
 * @date 2022/2/24 16:06
 */
@Service
public class AddressServiceImpl  extends ServiceImpl<AddressMapper, Matedata> implements AddressService {


    /**
     * @description: 根据用户id查询收货地址
     * @param
     * @return
     */
    @Override
    public List<MatedataRsp> getAddressByUserId(String userId) {
        LambdaQueryWrapper<Matedata> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Matedata::getUserId,userId);
        List<Matedata> list = baseMapper.selectList(wrapper);
        List<MatedataRsp> matedataRsps = JSON.parseArray(JSON.toJSONString(list), MatedataRsp.class);
        //过滤属于地址类型字典
        List<MatedataRsp> collect = matedataRsps.stream().filter(matedata -> DictionaryConstants.TYPE.equals(matedata.getType())).collect(Collectors.toList());
        List<MatedataRsp> list1 = collect.stream().map(address -> {
            address.setMap(JSON.parseObject(address.getContent()));
            return address;
        }).collect(Collectors.toList());
        return list1;
    }


    /**
     * @description: 添加收货地址
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addAddress(AddressRequest addressRequest, HttpServletRequest request) {
        Matedata matedata = new Matedata();
        matedata.setType(DictionaryConstants.TYPE);
        CustomAssert.notTrue(StringUtils.isNotEmpty(CurrentUserUtil.getUser().getId()), ResultCodeEnum.LOGIN_EXPIRED.getMessage());
        String id = CurrentUserUtil.getUser().getId();
        if (StringUtils.isEmpty(id)){
            JwtInfo info =null;
            if (request instanceof ShiroHttpServletRequest){
                String authorization = ((ShiroHttpServletRequest) request).getHeader("Authorization");
                info = JwtUtils.getMemberIdByJwtToken(authorization);
            } else {
                info = JwtUtils.getMemberIdByJwtToken((ServerHttpRequest) request);
            }
            matedata.setUserId(info.getId());
        } else {
            matedata.setUserId(id);
        }
        matedata.setContent(JSON.toJSONString(addressRequest));
        baseMapper.insert(matedata);
    }


    /**
     * @description: 修改收货地址
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void editAddress(AddressRequest addressRequest) {
        Matedata matedata = baseMapper.selectById(addressRequest.getId());
        CustomAssert.notTrue(ObjectUtils.isNotEmpty(matedata),ResultCodeEnum.ADDRESS_NOT_EXISTENT.getMessage());
        matedata.setContent(JSON.toJSONString(addressRequest));
        baseMapper.updateById(matedata);
    }


    /**
     * @description: 删除地址
     * @param
     * @return
     */

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteAddress(String id) {
        Matedata matedata = baseMapper.selectById(id);
        CustomAssert.notTrue(ObjectUtils.isNotEmpty(matedata),ResultCodeEnum.ADDRESS_NOT_EXISTENT.getMessage());
        baseMapper.deleteById(matedata);
    }
}
